<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="displayModuleTitle"
    width="1000px"
    @cancel="opSuccess"
  >
    <a-form
      ref="formRef"
      :scrollToFirstError="true"
      :model="hazardBasicInfo"
      :label-col="{ style: 'width: 130px' }"
      style="margin-top: 20px"
    >
      <a-row>
        <a-col :span="11">
          <a-form-item label="辨识/发现日期" name="tm" :rules="[{ required: true }]">
            <a-date-picker v-model:value="hazardBasicInfo.tm" valueFormat="YYYY-MM-DD" />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="辨识/发现人员" name="username" :rules="[{ required: true }]">
            <a-input v-model:value="hazardBasicInfo.username" />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="单元" name="unitname" :rules="[{ required: true }]">
            <a-input v-model:value="hazardBasicInfo.unitname" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="具体部位" name="position">
            <a-input v-model:value="hazardBasicInfo.position" />
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item label="类别" name="categorycode" :rules="[{ required: true }]">
            <a-input v-model:value="hazardBasicInfo.categoryname" disabled v-if="mode !== 'add'" />
            <a-select
              v-else
              :fieldNames="{ label: 'name', value: 'code' }"
              v-model:value="hazardBasicInfo.categorycode"
              :options="hazardOptions.filter((item) => item.level == 1)"
              @change="
                (e) => {
                  hazardBasicInfo.projectcode = '';
                  hazardBasicInfo.itemcode = '';
                  hazardBasicInfo.couse = '';
                  hazardBasicInfo.categoryname = hazardOptions.filter(
                    (item) => item.code == e,
                  )[0].name;
                }
              "
            />
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item label="项目" name="projectcode" :rules="[{ required: true }]">
            <a-input v-model:value="hazardBasicInfo.projectname" disabled v-if="mode !== 'add'" />
            <a-select
              v-else
              :fieldNames="{ label: 'name', value: 'code' }"
              v-model:value="hazardBasicInfo.projectcode"
              :options="
                hazardOptions.filter(
                  (item) => item.level == 2 && item.fatherId == hazardBasicInfo.categorycode,
                )
              "
              @change="
                (e) => {
                  hazardBasicInfo.itemcode = '';
                  hazardBasicInfo.couse = '';
                  hazardBasicInfo.projectname = hazardOptions.filter(
                    (item) => item.code == e,
                  )[0].name;
                }
              "
            />
          </a-form-item>
        </a-col>
        <a-col :span="8"
          ><a-form-item label="危险源" name="itemcode" :rules="[{ required: true }]">
            <a-input v-model:value="hazardBasicInfo.itemname" disabled v-if="mode !== 'add'" />
            <a-select
              v-else
              @change="addHazardChange"
              :fieldNames="{ label: 'name', value: 'code' }"
              v-model:value="hazardBasicInfo.itemcode"
              :options="
                hazardOptions.filter(
                  (item) => item.level == 3 && item.fatherId == hazardBasicInfo.projectcode,
                )
              "
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="是否重大危险源" name="ismajor" :rules="[{ required: true }]"
            ><a-radio-group
              v-model:value="hazardBasicInfo.ismajor"
              :disabled="mode !== 'add'"
              class="ismajorButton"
            >
              <a-radio-button :value="false">一般危险源</a-radio-button>
              <a-radio-button :value="true">重大危险源</a-radio-button>
            </a-radio-group>
          </a-form-item></a-col
        >
        <a-col :span="11">
          <a-form-item label="来源任务" name="taskitem">
            <a-select
              v-model:value="hazardBasicInfo.taskitemid"
              :options="taskOption"
              :fieldNames="{ label: 'itemname', value: 'itemid' }"
            ></a-select> </a-form-item
        ></a-col>
        <a-col :span="22"
          ><a-form-item label="事故诱因" name="couse"
            ><a-input v-model:value="hazardBasicInfo.couse" :disabled="mode !== 'add'" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <BasicForm @register="registerIdentifyForm" style="margin-top: 5px" />
    <template #footer>
      <div
        v-if="mode !== 'add' && currentIndex !== null && hazardList.length > 0"
        class="steps-action"
      >
        <a-button
          @click="switchHazard('pre')"
          v-if="mode !== 'add' && currentIndex !== null && hazardList.length > 0"
          ><LeftOutlined />上一个危险源</a-button
        >
        <div>
          <a-button type="primary" size="medium" @click="validateForm()">完成填报</a-button>
          <a-button size="medium" @click="closeModal">取消填报</a-button>
        </div>
        <a-button
          @click="switchHazard('next')"
          v-if="mode !== 'add' && currentIndex !== null && hazardList.length > 0"
          >下一个危险源<RightOutlined
        /></a-button>
      </div>
      <div v-else>
        <a-button type="primary" size="medium" @click="validateForm()">完成填报</a-button>
        <a-button size="medium" @click="opSuccess">取消填报</a-button>
      </div>
    </template>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, onMounted, ref, unref, watch } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getOneHazardInfo, addIdentifyRecord } from '/@/api/ehs/hazard';
  import { ExclamationCircleOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons-vue';
  import { identifyFormSchema } from './hazard.data';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import type { FormInstance } from 'ant-design-vue';
  import { queryDangerDbTreeList } from '/@/api/ehs/templateHazard';
  import { queryUnitTaskItem } from '/@/api/ehs/taskConsole';
  const { createInfoModal, createMessage, createErrorModal } = useMessage();
  import moment from 'moment';
  import { useUserStore } from '/@/store/modules/user';
  export default defineComponent({
    components: { BasicModal, BasicForm, ExclamationCircleOutlined, LeftOutlined, RightOutlined },
    name: 'HazardIndentifyModal',
    emits: ['register', 'success'],
    props: ['orgcode'],
    setup(props, { emit }) {
      const formRef = ref<FormInstance>();
      const userStore = useUserStore();
      const { realName = '', avatar, desc } = userStore.getUserInfo || {};
      const identifyOptions = ref();
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref();
      const taskOption = ref([]);
      const hazardBasicInfo = ref({
        unitid: '',
        unitname: '',
        categoryname: '',
        categorycode: '',
        projectname: '',
        projectcode: '',
        hazardname: '',
        hazardid: '',
        itemname: '',
        itemcode: '',
        ismajor: false,
        taskitemid: '',
        taskitemname: '',
        couse: '',
        tm: moment().format('YYYY-MM-DD'),
        position: '',
        username: '',
      });
      const currentIndex = ref(); // 现在操作的数组索引
      const hazardList = ref([]); // 要操作的危险源清单数组
      const hazardOptions = ref([]); // 当新增时,存储了可选择的当前导则库下的类别项目清单
      // 是新增危险源辨识还是全面辨识的标识
      const mode = ref('');
      const [
        registerIdentifyForm,
        {
          setFieldsValue: setIdentifyValue,
          validate: validateIdentify,
          updateSchema: updateIdentifySchema,
          resetFields: resetIdentify,
        },
      ] = useForm({
        labelWidth: 130,
        schemas: identifyFormSchema,
        showActionButtonGroup: false,
        scrollToFirstError: true,
      });
      const [register, { closeModal, changeLoading }] = useModalInner((data) => {
        console.log(data, 'data');
        dataId.value = null;
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          mode.value = data.dataId !== null ? 'identify' : 'add';
          //接收父组件传递的数据
          dataId.value = data.dataId;
          currentIndex.value = data.index;
          hazardList.value = data.hazardList;
          hazardBasicInfo.value.unitid = data.unitid;
          hazardBasicInfo.value.unitname = data.unitname;
          queryUnitTaskItem({
            unitid: hazardBasicInfo.value.unitid,
            status: 2,
            begintm: moment().startOf('year').format('YYYY-MM-DD'),
            endtm: moment().endOf('year').format('YYYY-MM-DD'),
          }).then((res) => {
            taskOption.value = res;
          });
          // 获取危险源完整信息
          if (dataId.value) {
            // 直接辨识非新增
            getOneHazardInfo(dataId.value).then((res) => {
              //将附件的字符串json对象化
              res.attachment = res && res.attachment ? JSON.parse(res.attachment) : [];
              res.undercontrol = res.identificationresult == 2 ? false : true;
              let unsafefactor = [];
              if (res.undercontrol !== null && !res.undercontrol) {
                [1, 2, 4].forEach((item) => {
                  if ((res.unsafefactor & item) == item) {
                    unsafefactor.push(item);
                  }
                });
              }
              // 有的数据有记录,有的数据可能为null,要区分判断一下
              Object.keys(hazardBasicInfo.value).forEach((item) => {
                hazardBasicInfo.value[item] = res[item];
              });
              hazardBasicInfo.value.unitid = res.unitid;
              hazardBasicInfo.value.unitname = res.unitname;
              hazardBasicInfo.value.tm =
                moment(res.recentidentificationtm).format('YYYY-MM-DD') ??
                moment().format('YYYY-MM-DD');
              // 过滤为空字段赋值
              let param = res
                ? Object.keys(res)
                    .filter((key) => res[key] !== null)
                    .reduce((acc, key) => ({ ...acc, [key]: res[key] }), {})
                : {};
              console.log(param, 'param');
              hazardBasicInfo.value.username = res.username ?? realName;
              setIdentifyValue({
                ...param,
                title: res.unitname + (res.position ?? '') + res.hazardname + (res.couse ?? ''),
                identificationresult:
                  param.identificationresult == 2 ? 1 : param.identificationresult ?? 0,
                unsafefactor: unsafefactor,
              });
            });
          } else {
            console.log(data, 'data');
            hazardBasicInfo.value.username = realName;
            setIdentifyValue({
              unitname: hazardBasicInfo.value.unitname,
            });
            // 新增危险源,要使用单元所在分类使用的导则库下的分类项目以及危险源信息
            queryDangerDbTreeList({ hdbcd: data.hazardDb, keytype: 0 }).then((res) => {
              hazardOptions.value = treeToArray(res);
            });
          }
        }
      });

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      async function validateForm() {
        // 辨识危险源表单提交
        try {
          const values = await validateIdentify();
          // 基础信息表单验证,验证后进行辨识
          formRef.value
            .validate()
            .then(() => {
              changeLoading(true);
              if (
                values.undercontrol !== undefined &&
                values.undercontrol !== null &&
                !values.undercontrol
              ) {
                values.unsafefactor = values.unsafefactor.reduce((accumulator, currentValue) => {
                  return accumulator + currentValue;
                }, 0);
              }
              //验证过后的表单数据对其中的文件ID集合信息进行修改
              let fileIds = '';
              if (values.attachment && values.attachment.length > 0x0) {
                //将json对象转换为字符串
                fileIds = JSON.stringify(values.attachment);
              }
              values.attachment = fileIds;
              if (hazardBasicInfo.value.taskitemid) {
                hazardBasicInfo.value.taskitemname = taskOption.value.find(
                  (item) => (item.itemid = hazardBasicInfo.value.taskitemid),
                ).itemname;
              }
              addIdentifyRecord({
                ...hazardBasicInfo.value,
                ...values,
                orgcode: props.orgcode,
                identificationresult:
                  values.identificationresult == 1 && !values.undercontrol
                    ? 2
                    : values.identificationresult,
                hazardid: dataId.value,
                unitid: hazardBasicInfo.value.unitid,
                unitname: hazardBasicInfo.value.unitname,
              })
                .then((res) => {
                  if (res.success) {
                    changeLoading(false);
                    createInfoModal({ title: '提示', content: res.msg });
                    if (
                      mode.value == 'add' ||
                      (currentIndex.value == null && hazardList.value.length == 0)
                    ) {
                      opSuccess();
                    }
                  } else {
                    createErrorModal({ title: '提示', content: res.msg });
                    changeLoading(false);
                  }
                })
                .catch((e) => {
                  changeLoading(false);
                  createMessage.error('辨识失败');
                });
            })
            .catch((e) => {
              createMessage.error(e.errorFields[0].errors[0]);
            });
        } catch (e) {
          createMessage.error(e.errorFields[0].errors[0]);
        }
      }
      function opSuccess() {
        formRef.value.resetFields();
        resetIdentify();
        emit('success');
        closeModal();
      }

      // 切换危险源(上一个下一个)
      function switchHazard(op) {
        if (op == 'pre') {
          // 点击上一个危险源按钮
          if (currentIndex.value == 0)
            return createMessage.error('此危险源为第一个,无上一个危险源');
          else currentIndex.value = currentIndex.value - 1;
        } else {
          // 点击下一个危险源按钮
          if (currentIndex.value + 1 == hazardList.value.length)
            return createMessage.error('此危险源为最后一个,无下一个危险源');
          else currentIndex.value = currentIndex.value + 1;
        }
        // 更新弹窗title以及dataId
        qcUnifyProps.value.operateString = `(当前操作第${currentIndex.value + 1}个,共${
          hazardList.value.length
        }个)`;
        dataId.value = hazardList.value[currentIndex.value].hazardid;
        resetIdentify();
        // 获取新的危险源信息
        getOneHazardInfo(dataId.value).then((res) => {
          //将附件的字符串json对象化
          res.attachment = res && res.attachment ? JSON.parse(res.attachment) : [];
          res.undercontrol = res.identificationresult == 2 ? false : true;
          let unsafefactor = [];
          if (res.undercontrol !== null && !res.undercontrol) {
            [1, 2, 4].forEach((item) => {
              if ((res.unsafefactor & item) == item) {
                unsafefactor.push(item);
              }
            });
          }
          // 有的数据有记录,有的数据可能为null,要区分判断一下
          Object.keys(hazardBasicInfo.value).forEach((item) => {
            hazardBasicInfo.value[item] = res[item];
          });
          hazardBasicInfo.value.unitid = res.unitid;
          hazardBasicInfo.value.unitname = res.unitname;
          hazardBasicInfo.value.tm =
            moment(res.recentidentificationtm).format('YYYY-MM-DD') ??
            moment().format('YYYY-MM-DD');
          // 过滤为空字段赋值
          let param = res
            ? Object.keys(res)
                .filter((key) => res[key] !== null)
                .reduce((acc, key) => ({ ...acc, [key]: res[key] }), {})
            : {};
          console.log(param, 'param');
          setIdentifyValue({
            ...param,
            title: res.unitname + (res.position ?? '') + res.hazardname + (res.couse ?? ''),
            identificationresult:
              param.identificationresult == 2 ? 1 : param.identificationresult ?? 0,
            unsafefactor: unsafefactor,
          });
        });
      }
      // 新增危险源时,选择的危险源变化触发的函数(选择的可能是辨识过的已有辨识记录的危险源,这个时候要把它之前的辨识记录赋值回来)
      function addHazardChange(e) {
        dataId.value = null;
        hazardBasicInfo.value.couse = '';
        hazardBasicInfo.value.itemname = hazardOptions.value.filter(
          (item) => item.code == e,
        )[0].name;
        hazardBasicInfo.value.hazardname = hazardBasicInfo.value.itemname;
        resetIdentify();
        let hazard = hazardList.value?.find((item) => item.itemcode == e);
        if (hazard?.hazardid) {
          // 获取新的危险源信息
          getOneHazardInfo(hazard.hazardid).then((res) => {
            //将附件的字符串json对象化
            res.attachment = res && res.attachment ? JSON.parse(res.attachment) : [];
            res.undercontrol = res.identificationresult == 2 ? false : true;
            let unsafefactor = [];
            if (res.undercontrol !== null && !res.undercontrol) {
              [1, 2, 4].forEach((item) => {
                if ((res.unsafefactor & item) == item) {
                  unsafefactor.push(item);
                }
              });
            }
            // 有的数据有记录,有的数据可能为null,要区分判断一下
            Object.keys(hazardBasicInfo.value).forEach((item) => {
              hazardBasicInfo.value[item] = res[item];
            });
            hazardBasicInfo.value.unitid = res.unitid;
            hazardBasicInfo.value.unitname = res.unitname;
            hazardBasicInfo.value.tm =
              moment(res.recentidentificationtm).format('YYYY-MM-DD') ??
              moment().format('YYYY-MM-DD');
            // 过滤为空字段赋值
            let param = res
              ? Object.keys(res)
                  .filter((key) => res[key] !== null)
                  .reduce((acc, key) => ({ ...acc, [key]: res[key] }), {})
              : {};
            console.log(param, 'param');
            setIdentifyValue({
              ...param,
              title:
                res.unitname +
                (hazardBasicInfo.value.position ?? '') +
                res.hazardname +
                (hazardBasicInfo.value.couse ?? ''),
              identificationresult:
                param.identificationresult == 2 ? 1 : param.identificationresult ?? 0,
              unsafefactor: unsafefactor,
            });
            createMessage.success('已自动代入危险源台账信息');
          });
        } else {
          // 没有的话就在hazardOptions中过滤出itemcode为e的项,把基本信息赋值回来
          let hazard = hazardOptions.value.find((item) => item.code == e);
          // 有的数据有记录,有的数据可能为null,要区分判断一下
          Object.keys(hazardBasicInfo.value).forEach((item) => {
            if (hazard[item]) {
              hazardBasicInfo.value[item] = hazard[item];
            }
          });
          hazardBasicInfo.value.couse = hazard.cause;
          setIdentifyValue({
            ...hazard,
            identificationresult: 1,
            unitname: hazardBasicInfo.value.unitname,
            maycouseharm: hazard.consequence,
            title:
              hazardBasicInfo.value.unitname +
              (hazardBasicInfo.value.position ?? '') +
              hazard.name +
              (hazardBasicInfo.value.couse ?? ''),
          });
          createMessage.success('已自动代入危险源导则库信息');
          console.log(hazard, 'hazard');
        }
      }
      // tree结构扁平化
      function treeToArray(treeNodes) {
        let result = [];

        //递归函数 traverse，用于处理单个节点
        function traverse(node, fatherId) {
          const newNode = { ...node };
          if (fatherId) {
            newNode.fatherId = fatherId;
          }
          delete newNode.children;
          // 将没有子节点的新节点添加到结果数组中
          result.push(newNode);

          // 如果当前节点包含 children 属性（即有子节点）
          if (node.children) {
            node.children.forEach((item) => {
              traverse(item, newNode.code);
            });
          }
        }

        treeNodes.forEach(traverse);

        return result;
      }

      watch(
        () => [hazardBasicInfo.value.couse, hazardBasicInfo.value.position],
        ([couse, position]) => {
          setIdentifyValue({
            title:
              hazardBasicInfo.value.unitname +
              (position ?? '') +
              hazardBasicInfo.value.hazardname +
              (couse ?? ''),
          });
        },
      );

      onMounted(() => {
        queryEnumOptions('EhsHazardIndentificationResultTypeEnum').then((res) => {
          // console.log('option res', res);
          if (res != undefined && res != null && res.length > 0x0) {
            let op = res[0].options.map((option) => {
              return {
                value: Number(option.key),
                label: option.value,
              };
            });
            identifyOptions.value = op;
          }
        });
      });
      return {
        formRef,
        mode,
        identifyOptions,
        register,
        registerIdentifyForm,
        hazardList,
        currentIndex,
        validateForm,
        hazardOptions,
        opSuccess,
        switchHazard,
        hazardBasicInfo,
        displayModuleTitle,
        addHazardChange,
        closeModal,
        taskOption,
      };
    },
  });
</script>
<style scoped>
  .steps-action {
    display: flex;
    justify-content: space-around;
    align-items: flex-end;
  }

  .ant-radio-button-wrapper.ant-radio-button-wrapper-checked {
    color: #000;
  }
  .ant-radio-group-solid
    .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):hover {
    color: #000;
  }
  .ismajorButton .ant-radio-button-wrapper:nth-child(1).ant-radio-button-wrapper-checked {
    background-color: rgb(59, 89, 153);
    color: #fff;
    border: blue;
  }
  .ismajorButton .ant-radio-button-wrapper:nth-child(2).ant-radio-button-wrapper-checked {
    background-color: rgb(205, 32, 31);
    color: #fff;
    border: red;
  }
  .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled)::before {
    background: rgb(203, 203, 203);
  }
</style>
